/**
 * Copyright (c) 2002-2011 旭鸣信息
 * All rights reserved. 
 * File：ArticlesSortDaoImpl.java
 * History:
 *       May 11, 2012: Initially created, liuzhi.
 */
package com.xteam.ecsystem.dao.Impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xteam.ecsystem.base.SystemContent;
import com.xteam.ecsystem.dao.IArticlesSortDao;
import com.xteam.ecsystem.entities.BaseArticleGroup;
import com.xteam.ecsystem.entities.BaseArticleInfo;
import com.xteam.ecsystem.utils.PageCenterStation;

/**
 * 文章分类数据访问实现类
 * 
 * @author liuzhi
 * 
 */
@Repository
public class ArticlesSortDaoImpl extends DDLPrefix implements IArticlesSortDao {

	@SuppressWarnings("unchecked")
	@Autowired
	private BaseDaoImpl baseDao;

	@SuppressWarnings("unchecked")
	public String getBasInfoList(int pageIndex, int pageSize, String bagName) {
		JSONObject jo = new JSONObject();
		try {
			List list = new ArrayList();

			String hql = SQL_FROM + BaseArticleGroup.REF + SQL_WHERE + " 1=1 ";
			String countHQL = SQL_SELECT + " count(*) " + SQL_FROM
					+ BaseArticleGroup.REF + SQL_WHERE + " 1=1 ";

			if (bagName != null && bagName.length() > 0
					&& !bagName.equals("undefined")
					&& !bagName.equals("null")) {
				hql += SQL_AND + " bagName " + SQL_LIKE + " ? ";
				countHQL += SQL_AND + " bagName " + SQL_LIKE + " ? ";
				list.add("%" + bagName + "%");

			}

			PageCenterStation<?> p = (PageCenterStation<?>) this.baseDao.queryList(countHQL, hql, list
					.toArray(), pageIndex * pageSize, pageSize);
			
			jo = JSONObject.fromObject(p);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return jo.toString();
	}
	
	@SuppressWarnings("unchecked")
	public void delObject(String ids) {
		Class clazz = null;
		try {
			clazz = Class.forName("com.xteam.ecsystem.entities.BaseArticleGroup");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		List list = new ArrayList();
		String oId[] = ids.split(",");
		for (String id : oId) {
			Object obj = this.baseDao.get(clazz, id);
			if (obj != null) {
				list.add(obj);
			}
		}
		this.baseDao.deleteAll(list);
	}

	/**
	 * @see com.xteam.ecsystem.dao.IArticlesSortDao#saveOrUpdateObject(java.lang.Object,
	 *      java.lang.String)
	 */
	public void saveOrUpdateObject(Object obj, String id) {
		try {
			if (id != null && !id.equals("") && id.length() > 0) {
				this.baseDao.update(obj);
			} else {
				this.baseDao.save(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public String getBasInfoById(String bagId) {
		JSONObject jo = new JSONObject();
		try {
			List list = new ArrayList();

			String hql = SQL_FROM + BaseArticleGroup.REF + SQL_WHERE + " 1=1 "
					+ SQL_AND + " bagId=?";
			list = this.baseDao.find(hql, new Object[] { bagId });

			if (list != null && list.size() > 0) {
				jo = JSONObject.fromObject((BaseArticleGroup) list.get(0));
				return jo.toString();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}

	@SuppressWarnings("unchecked")
	public void updateBasStateById(String bagId) {
		Class clazz = null;
		try {
			clazz = Class.forName("com.xteam.ecsystem.entities.BaseArticleGroup");

			BaseArticleGroup articlesSort = (BaseArticleGroup) this.baseDao.get(
					clazz, bagId);
			if (articlesSort.getBagState() == 1) {
				articlesSort.setBagState(0);
			} else {
				articlesSort.setBagState(1);
			}

			this.baseDao.saveOrUpdate(articlesSort);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public JSONArray getBasJsonArray(BaseArticleGroup articlesSort,
			String bagParent) {
		JSONArray jarray = new JSONArray();

		if (articlesSort != null) {
			JSONObject obj = new JSONObject();

			obj.put("bagId", articlesSort.getBagId());
			obj.put("bagParent", articlesSort.getBagParent());
			obj.put("bagName", articlesSort.getBagName());
			obj.put("bagOrder", articlesSort.getBagOrder());
			obj.put("bagState", articlesSort.getBagState());

			String hql_r = SQL_FROM + BaseArticleGroup.REF + SQL_WHERE
					+ " bagParent =?";
			List list_r = this.baseDao.find(hql_r, new Object[] { bagParent });
			if (list_r.size() > 0) {
				JSONObject obj_r = new JSONObject();

				for (int i = 0; i < list_r.size(); i++) {
					BaseArticleGroup sort = (BaseArticleGroup) list_r.get(i);

					JSONArray jarray_r = getBasJsonArray(sort, sort.getBagId());

					obj_r.accumulate("temp2", jarray_r);
					if (obj_r.get("temp2") instanceof JSONArray) {
						int size = obj_r.getJSONArray("temp2").size();
						for (int j = 0; j < size; j++) {
							if (obj_r.getJSONArray("temp2").get(j) instanceof JSONArray) {
								JSONObject obj3 = obj_r.getJSONArray("temp2")
										.getJSONArray(j).getJSONObject(0);
								obj_r.getJSONArray("temp2").remove(j);
								obj_r.getJSONArray("temp2").add(j, obj3);
							}
						}
					}

					obj.put("children", obj_r.get("temp2"));
				}
			}

			jarray.add(obj);

		} else {
			List bagIdList = new ArrayList();
			String hql = SQL_SELECT + " bagId " + SQL_FROM + BaseArticleGroup.REF
					+ SQL_GROUPBY + " bagId " + SQL_ORDERBY + " bagId asc ";

			bagIdList = this.baseDao.find(hql);

			for (int i = 0; i < bagIdList.size(); i++) {
				String bagId = (String) bagIdList.get(i);

				String hql_1 = SQL_FROM + BaseArticleGroup.REF + SQL_WHERE
						+ " bagId=? " + SQL_AND + " bagParent='0' "; //之前为0
				// 查询所有父节点为0的文章分类信息
				List basList = this.baseDao.find(hql_1, new Object[] { bagId });

				JSONObject basObj[] = new JSONObject[basList.size()];
				for (int j = 0; j < basList.size(); j++) {
					basObj[j] = new JSONObject();

					BaseArticleGroup baSort = (BaseArticleGroup) basList.get(j);

					basObj[j].put("bagId", baSort.getBagId());
					basObj[j].put("bagParent", baSort.getBagParent());
					basObj[j].put("bagName", baSort.getBagName());
					basObj[j].put("bagOrder", baSort.getBagOrder());
					basObj[j].put("bagState", baSort.getBagState());

					String hql_2 = SQL_FROM + BaseArticleGroup.REF + SQL_WHERE
							+ " bagParent=?";
					// 查询所有次级孩子节点的文章分类信息
					List childList = this.baseDao.find(hql_2,
							new Object[] { baSort.getBagId() });
					if (childList != null && childList.size() > 0) {
						JSONObject childObj = new JSONObject();

						for (int h = 0; h < childList.size(); h++) {
							BaseArticleGroup childInfo = (BaseArticleGroup) childList.get(h);

							JSONArray jarray2 = getBasJsonArray(childInfo,	childInfo.getBagId());

							childObj.accumulate("temp", jarray2.get(0));
						}

						if (childObj.get("temp") instanceof JSONObject) {
							JSONArray jarray3 = new JSONArray();
							jarray3.add(0, childObj.get("temp"));
							basObj[j].put("children", jarray3);
						} else {
							basObj[j].put("children", childObj.get("temp"));
						}
					}

					jarray.element(basObj[j]);
				}
			}

		}

		return jarray;
	}

	@SuppressWarnings("unchecked")
	public String lazyLoadBasTree(String bagParent) {
		if (bagParent == null || "".equals(bagParent)
				|| "null".equals(bagParent) || "undefined".equals(bagParent)) {
			bagParent = "0"; //-1 
		}
		
		List basTreeList = new ArrayList(); 

		//获取下一级节点
		String hql = SQL_FROM + BaseArticleGroup.REF + SQL_WHERE + " bagParent=? ";
		ArrayList list = (ArrayList)this.baseDao.find(hql, new Object[]{bagParent});
		
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				BaseArticleGroup bas = (BaseArticleGroup)list.get(i);
				
				map.put("bagId", bas.getBagId());
				map.put("bagParent", bas.getBagParent());
				map.put("bagName", bas.getBagName());
				basTreeList.add(map);
			}
		}
		
		// 判断节点，是否有子节点。如果有，则处理isLeaf和expanded。
		for (int i = 0, j = basTreeList.size(); i < j; i++) {
			HashMap node = (HashMap) basTreeList.get(i);
			String nodeId = node.get("bagId").toString();

			String hql2 = SQL_FROM + BaseArticleGroup.REF + SQL_WHERE	+ " bagParent=? ";
			ArrayList nodeList = (ArrayList) this.baseDao.find(hql2, new Object[] { nodeId });

			if (nodeList != null && nodeList.size() > 0) {
				node.put("isLeaf", false);
				node.put("expanded", false);
			}
		}

		// 返回处理结果
		String bggTree = PluSoft.Utils.JSON.Encode(basTreeList);
		return bggTree;
	}

	@SuppressWarnings("unchecked")
	public String lazyLoadBasTreeGrid(String bagParent) {
		if (bagParent == null || "".equals(bagParent)
				|| "null".equals(bagParent) || "undefined".equals(bagParent)) {
			bagParent = "0"; //-1 
		}
		
		List basTreeList = new ArrayList(); 

		//获取下一级节点
		//一：使用hql语句，返回javabean对象
		String hql = SQL_FROM + BaseArticleGroup.REF + SQL_WHERE + " bagParent=? ";
		ArrayList list = (ArrayList)this.baseDao.find(hql, new Object[]{bagParent});
		
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				BaseArticleGroup bgg = (BaseArticleGroup)list.get(i);
				
				map.put("bagId", bgg.getBagId());
				map.put("bagParent", bgg.getBagParent());
				map.put("bagName", bgg.getBagName());
				map.put("bagOrder", bgg.getBagOrder());
				map.put("bagState", bgg.getBagState());
				basTreeList.add(map);
			}
		}

		// 判断节点，是否有子节点。如果有，则处理isLeaf和expanded。
		for (int i = 0, j = basTreeList.size(); i < j; i++) {
			HashMap node = (HashMap) basTreeList.get(i);
			String nodeId = node.get("bagId").toString();

			String hql2 = SQL_FROM + BaseArticleGroup.REF + SQL_WHERE	+ " bagParent=? ";
			ArrayList nodeList = (ArrayList) this.baseDao.find(hql2, new Object[] { nodeId });

			if (nodeList != null && nodeList.size() > 0) {
				node.put("isLeaf", false);
				node.put("expanded", false);
			}
		}

		// 返回处理结果
		String bggTree = PluSoft.Utils.JSON.Encode(basTreeList);
		return bggTree;
	}
	
	/**
	 * @see com.xteam.ecsystem.dao.IArticlesSortDao#getSystemContent(int, java.lang.String, java.lang.String, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, String>> getSystemContent(int state, String value, String text, String parent) {
		String hql = "select bagId as " + value + ", bagName as " + text + ", bagParent as " + parent + 
			" from BaseArticleGroup where bagState = " + state;
		return this.baseDao.queryListInMap(hql);
	}
	
	/**
	 * @see com.xteam.ecsystem.dao.IArticlesSortDao#getSystemContents(java.lang.String, int, int, int)
	 */
	@SuppressWarnings("unchecked")
	public PageCenterStation<SystemContent> getSystemContents(String name, int state, int first, int max) {
		String suffix = " from base_article_group c left join base_article_group p on c.bag_parent = p.bag_id " + 
			"where c.bag_state = " + state;
		if (name != null && !"".equals(name)) {
			suffix += " and c.bag_name like '%" + name + "%'";
		}
		
		String countSql = "select count(c.bag_id)" + suffix;
		long count = this.baseDao.queryCountWithSql(countSql);
		
		List<SystemContent> list = new ArrayList<SystemContent>();
		if (count > 0) {
			String querySql = "select c.bag_id as value, c.bag_name as text, p.bag_name as parent" + suffix;
			List<Object[]> data = this.baseDao.queryListWithSql(querySql);
			if (data != null) {
				for (Object[] o : data) {
					String value = (o[0] == null) ? null : o[0].toString();
					String text = (o[1] == null) ? null : o[1].toString();
					String parent = (o[2] == null) ? null : o[2].toString();
					list.add(new SystemContent(value, text, parent));
				}
			}
		}
		
		return new PageCenterStation<SystemContent>(count, list);
	}
	
	@SuppressWarnings("unchecked")
	public boolean getBaiByBas(String bagIds){
		boolean isUsed = false;
		List list = new ArrayList();
		String hql = "";
		
		try {
			String oId[] = bagIds.split(",");
			for (String id : oId) {
				hql = SQL_FROM + BaseArticleInfo.REF + SQL_WHERE + "baiGroup = ?";
				list = this.baseDao.find(hql, new Object[]{id});
				
				if (list != null && !list.isEmpty()) {
					isUsed = true;
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return isUsed;
	}
}
